//
//  AppSetting.m
//  WeightMaster
//
//  Created by sungeo on 15/8/14.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "WMAppSetting.h"
#import "WMWeight.h"
#import <TMDiskCache.h>
#import <NSObject+GLPubSub.h>
#import <EXTScope.h>

// 通知消息
NSString * const WMSettingsChanged = @"WMSettingsChanged";
NSString * const WMGotSettingFromiCloud = @"GotSettingFromiCloud";
NSString * const WMCoverChanged = @"WMCoverChanged";

static NSString * const AppSettingsKey = @"AppSettingsKey";
static float const DefaultHeight = 0;
static float const DefaultWeight = 0;

// 存储在云端记录的 UUID
static NSString * const WMSettingsUUID = @"liuwanwei-huanghouyu-maoyu";

// 云端记录类型
static NSString * const WMRecordTypeSettings = @"WMRecordTypeSettings";

// 存储在云端记录的 fields
static NSString * const GenderKey = @"Gender";
static NSString * const HeightKey = @"Height";
static NSString * const GoalWeightKey = @"GoalWeight";
static NSString * const WeightUnitKey = @"UnitKey";

// 缓存在本地的封面图片的 ID
static NSString * const CoverImageID = @"CoverImageID";

@interface WMAppSetting(){
    BDiCloudManager * _iCloudManager;
    
    NSTimer * _syncTimer;
    
    UIImage * _coverImage;
}

@end

@implementation WMAppSetting

+ (instancetype)sharedInstance{
    static WMAppSetting * sInstance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (sInstance == nil) {
            
            // 先从本地缓存加载数据
            sInstance = [[self class] loadSettings];
            if (sInstance == nil) {
                sInstance = [[WMAppSetting alloc] init];
            }
            
            sInstance->_iCloudManager = [[BDiCloudManager alloc] init];
            sInstance->_iCloudManager.delegate = sInstance;
            
            sInstance->_syncTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:sInstance selector:@selector(syncDataToiCloud:) userInfo:nil repeats:YES];
        }
    });
    
    return sInstance;
}

+ (WMAppSetting *)loadSettings{
    id object = [[TMDiskCache sharedCache] objectForKey:AppSettingsKey];
    if (object && [object isKindOfClass:[WMAppSetting class]]) {
        WMAppSetting * appSetting = (WMAppSetting *)object;
        
        return appSetting;
    }else{
        return nil;
    }
}

- (instancetype)init{
    if (self = [super init]) {

        _gender = @(WMGenderFemale);
        _height = @(DefaultHeight);
        _goalWeight = @(DefaultWeight);
        _weightUnit = @(WMWeightUnitKiloGram);
    }
    
    return self;
}

- (CKRecordID *)recordID{
    return [[CKRecordID alloc] initWithRecordName:WMSettingsUUID];
}

- (void)queryDataFromiCloud{
    
    // TODO: 查询前判断是否开启 iCloud
    @weakify(self);
    CKRecordID * recordID = [self recordID];
    [_iCloudManager.privateDatabase fetchRecordWithID:recordID completionHandler:^(CKRecord * record, NSError * error){
        @strongify(self);
        if (record != nil) {
            if ([record.recordType isEqualToString:WMRecordTypeSettings]) {
                NSLog(@"从云端更新配置信息成功");
                
                self.gender = record[GenderKey];
                self.height = record[HeightKey];
                self.goalWeight = record[GoalWeightKey];
                self.weightUnit = record[WeightUnitKey];
                self.savedToiCloud = @(YES);
                
                [self publish:WMGotSettingFromiCloud];
                [self syncDataToDisk];
            }
        }else{
            if (error == nil || error.code == CKErrorUnknownItem) {
                NSLog(@"云端查询不到配置信息");
            }else{
                NSLog(@"从云端查询配置信息失败：%@", error);
            }
        }
    }];
}

- (void)syncData{
    _savedToiCloud = @(NO);    
    [self syncDataToDisk];
}

- (BOOL)isSetGoalWeight{
    if ([_goalWeight isEqualToNumber:@(DefaultWeight)]) {
        return NO;
    }else{
        return YES;
    }
}

#define CoverImageID @"WMCoverImage_freedom"
- (void)setCoverImage:(UIImage *)coverImage{
    if (coverImage == nil) {
        return;
    }
    
    NSData * data = UIImageJPEGRepresentation(coverImage, 0.75);
    
    NSURL *cachesDirectory = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
    NSString *temporaryName = [CoverImageID stringByAppendingPathExtension:@"jpeg"];
    NSURL *localURL = [cachesDirectory URLByAppendingPathComponent:temporaryName];
    [data writeToURL:localURL atomically:YES];

    _coverImage = coverImage;
    
    [self publish:WMCoverChanged];
}

- (UIImage *)coverImage{
    if (_coverImage) {
        return _coverImage;
    }
    
    NSURL *cachesDirectory = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
    NSString *temporaryName = [CoverImageID stringByAppendingPathExtension:@"jpeg"];
    NSURL *localURL = [cachesDirectory URLByAppendingPathComponent:temporaryName];
    if (! [[NSFileManager defaultManager] fileExistsAtPath:localURL.path]) {
        return nil;
    }
    
    _coverImage = [UIImage imageWithContentsOfFile:localURL.path];
    return _coverImage;
}


- (void)syncDataToDisk{
    [[TMDiskCache sharedCache] setObject:self forKey:AppSettingsKey];
    [self publish:WMSettingsChanged];    
}

- (void)syncDataToiCloud:(NSTimer *)timer{
    if ([_savedToiCloud boolValue] == YES) {
        return;
    }
    
    // 从这里开始，修改配置信息的更新方式，摆脱拖沓的 objc_setOss...
    if ([BDiCloudManager serviceReady]) {
        
        CKRecordID * recordID = [self recordID];
        @weakify(self);
        [_iCloudManager.privateDatabase fetchRecordWithID:recordID completionHandler:^(CKRecord * record, NSError * error){
            @strongify(self);
            if (record == nil) {
                record = [[CKRecord alloc] initWithRecordType:WMRecordTypeSettings recordID:recordID];
            }
            
            record[GenderKey] = _gender;
            record[HeightKey] = _height;
            record[GoalWeightKey] = _goalWeight;
            record[WeightUnitKey] = _weightUnit;
            
            [_iCloudManager.privateDatabase saveRecord:record completionHandler:^(CKRecord * record, NSError * error){
                if (error == nil) {
                    // 保存成功
                    self.savedToiCloud = @(YES);
                    [self syncDataToDisk];
                    NSLog(@"保存配置信息到 CloudKit 成功");
                    
                }else{
                    // 保存失败
                    NSLog(@"保存配置信息到 CloudKit 失败：%@", error);
                }
            }];
        }];
        
    }
//    else{
//        [self queryDataFromiCloud];
//    }
}


#pragma mark - BD iCloud data source

- (instancetype)initFromiCloudRecordObject:(CKRecord *)record{
    [NSException raise:@"" format:@"不该使用这个函数"];
    return nil;
}

#pragma mark - BD iCloud delegate

- (void)didReceiveRecords:(NSArray *)results{
    NSInteger count = results.count;
    if (count == 1) {
        CKRecord * record = results[0];
        if ([record.recordType isEqualToString:AppSettingsKey]) {
            NSLog(@"查询到 WMAppSetting，更新配置");
            
            self.gender = record[GenderKey];
            self.height = record[HeightKey];
            self.goalWeight = record[GoalWeightKey];
            self.weightUnit = record[WeightUnitKey];
            self.savedToiCloud = @(YES);
            
            [self publish:WMGotSettingFromiCloud];
            
            [self syncDataToDisk];
        }
        
    }else if (count > 1){
        NSLog(@"查询到的 WMAppSetting 记录异常，记录值应该等于 1");
    }else if (count == 0){
        // 某个 AppID 首次打开 App 后，会进到这里，表示查询成功，但没有结果。
        // ( 2015-8-19 用毛宇 iPhone4S 测试）
        NSLog(@"没有找到 WMAppSetting 记录");
    }
}

- (void)successfullySavedRecord:(CKRecord *)record{
    if ([record.recordType isEqualToString:AppSettingsKey]) {
        self.savedToiCloud = @(YES);
        [self syncDataToDisk];
        
        NSLog(@"保存配置信息到 CloudKit 成功");
    }
}

@end
